package com.mpp.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mpp.admin.entity.OnLineUser;
import com.mpp.admin.entity.PageEntity;
import com.mpp.admin.entity.User;
import com.mpp.admin.service.UserService;
import com.mpp.admin.shiro.RedisSessionDao;
import com.mpp.admin.util.Constant;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;


/**
 * @author mapp
 * @des
 * @date 2019/2/14
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisSessionDao sessionDAO;

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index() {
        return "user";
    }

    @RequestMapping("/getAll")
    @ResponseBody
    public PageEntity getAll(int page, int limit, User user) {
        return (PageEntity) userService.page(PageEntity.build(page, limit),
                new QueryWrapper<User>().eq(StringUtils.isNotBlank(user.getUsername()), "username", user.getUsername()));
    }

    // 在线用户
    @RequestMapping("/onLineUsersList")
    @ResponseBody
    public PageEntity onLineUsersList() {
        Collection<Session> sessionSet = sessionDAO.getActiveSessions();
        List<OnLineUser> onLineUsers = new LinkedList<>();
        for (Session session : sessionSet) {
            OnLineUser user = (OnLineUser) session.getAttribute(Constant.SHIRO_SESSION_ATTR);
            if (user != null) {
                onLineUsers.add(user);
            }
        }
        PageEntity pageEntity = new PageEntity(1, 10);
        pageEntity.setRecords(onLineUsers);
        return pageEntity;
    }

    @RequestMapping("/onLineUsers")
    public String onLineUsers() {
        return "onLineUsers";
    }

    /**
     * 强制下线
     * @param sessionId
     * @return
     */
    @RequestMapping("/userLayout")
    @ResponseBody
    public String userLayout(String sessionId) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(true);
        if (StringUtils.equals(sessionId, (String) session.getId())) {
            // 不能自己对自己下线
            return "不能对自己操作！";
        }
        sessionDAO.delete(sessionId);
        return "success";
    }

}
